﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using Web.Framework.Svc;
using System.Text;

namespace Web.Framework
{
    public class ExceptionManager
    {
        public static ExceptionManager Instance
        {
            get
            {
                return privateInstance;
            }
        }

        private static ExceptionManager privateInstance = new ExceptionManager();

        public IWebMessage WebMessager { get; set; }

        public void HandleException(Exception ex)
        {
            if (ex.GetType().Equals(typeof(FaultException<WebFrameworkFaultException>)))
            {
                FaultException<WebFrameworkFaultException> faultException = (FaultException<WebFrameworkFaultException>)ex;

                string message;
                if (faultException.Detail.IsBusinessException)
                {
                    message = faultException.Detail.Message;
                }
                else
                {
                    message = faultException.Detail.Message + Environment.NewLine + faultException.Detail.StackTrace;
                }

                WebMessager.ShowMessage(faultException.Detail.Title, message, WebMessageType.Error);
            }
            else
            {
                if (WebMessager != null)
                {
                    WebMessager.ShowMessage(GetExceptionMessage(ex) + GetExceptionStackTrace(ex), WebMessageType.Error);
                }
            }
        }

        public void ShowMessage(string message)
        {
            if (WebMessager != null)
            {
                WebMessager.ShowMessage(message, WebMessageType.Notification);
            }
        }

        public void ShowWarning(string message)
        {
            if (WebMessager != null)
            {
                WebMessager.ShowMessage(message, WebMessageType.Warning);
            }
        }

        public string GetExceptionMessage(Exception ex)
        {
            StringBuilder builder = new StringBuilder();

            Exception current = ex;
            while (current != null)
            {
                builder.Append(current.Message);
                current = current.InnerException;
            }

            return builder.ToString();
        }

        public string GetExceptionStackTrace(Exception ex)
        {
            StringBuilder builder = new StringBuilder();

            Exception current = ex;
            while (current != null)
            {
                builder.Append(current.StackTrace);
                current = current.InnerException;
            }

            return builder.ToString();
        }
    }
}